﻿using Com.Qiniu.ShopErp.App.Device.Print;
using Mengsk.ProxyDelivery.App.Device;
using Mengsk.ProxyDelivery.App.Domain;
using Mengsk.ProxyDelivery.App.Service;
using Mengsk.ProxyDelivery.Domain;
using Mengsk.ProxyDelivery.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Mengsk.ProxyDelivery.App.UI.Delivery
{
    /// <summary>
    /// ReturnUserControl.xaml 的交互逻辑
    /// </summary>
    public partial class RefusedUserControl : UserControl, IPlugin
    {
        private bool myLoaded = false;
        private OrderChangeService orderChangeService = ServiceContainer.GetService<OrderChangeService>();
        private OrderService orderService = ServiceContainer.GetService<OrderService>();
        private System.Collections.ObjectModel.ObservableCollection<OrderRefusedViewModel> orderRefuse = new System.Collections.ObjectModel.ObservableCollection<OrderRefusedViewModel>();
        private string COMMENT = "检查通过【大小码，定做,部分真皮厂家一般不退请注意】";
        public string Title
        {
            get { return "拒签收件"; }
        }

        public Control UIControl
        {
            get { return this; }
        }

        public RefusedUserControl()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (this.myLoaded)
            {
                return;
            }
            this.myLoaded = true;
            this.dgvOrderChanges.ItemsSource = this.orderRefuse;
            this.orderRefuse.CollectionChanged += orderChanges_CollectionChanged;
        }

        void orderChanges_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            this.tbTotalInfo.Text = "当前共:" + this.orderRefuse.Select(obj => obj.DeliveryNumber).Distinct().Count() + "条快递记录, 商品记录:" + this.orderRefuse.Count();
        }

        private void tbDeliveryNumber_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Enter)
            {
                e.Handled = false;
                return;
            }

            try
            {
                String deliveryNumber = this.tbDeliveryNumber.Text.Trim().ToUpper();
                if (deliveryNumber.Length < 1)
                {
                    return;
                }

                if (this.orderRefuse.FirstOrDefault(obj => obj.DeliveryNumber == deliveryNumber) != null)
                {
                    Speaker.Speak("已存在");
                    return;
                }

                //先读取发出信息
                var data = ServiceContainer.GetService<OrderService>().GetByDeliveryNumber(deliveryNumber);
                if (data != null && data.Datas.Count < 1)
                {
                    Speaker.Speak("未找到订单");
                    return;
                }

                if (data.Datas.Count != 1)
                {
                    Speaker.Speak("一个物流单号找到多个订单");
                    return;
                }

                var order = data.Datas[0];

                //空包
                if (order.OrderGoodss == null || order.OrderGoodss.Count < 1)
                {
                    OrderRefusedViewModel vm = new OrderRefusedViewModel
                     {
                         State = "",
                         OrderGoodsInfo = "",
                         DeliveryNumber = deliveryNumber,
                         DeliveryCompany = order.DeliveryCompany,
                         Comment = "",
                         Action = "删除",
                         Image = "",
                         Source = null,
                         SellerId = order.SellerId,
                     };
                    this.orderRefuse.Add(vm);
                    Speaker.Speak("已接受");
                    return;
                }

                foreach (var og in order.OrderGoodss)
                {
                    String image = "";
                    String goodsInfo = "";

                    goodsInfo = og.Vendor + " " + og.Number + " " + og.Edtion + " " + og.Color + " " + og.Size;
                    if (og.NumberId > 0)
                    {
                        var shoes = ServiceContainer.GetService<ShoesService>().GetById(og.NumberId);
                        if (shoes != null)
                        {
                            image = shoes.Image;
                        }
                    }

                    OrderRefusedViewModel vm = new OrderRefusedViewModel
                      {
                          State = "",
                          OrderGoodsInfo = goodsInfo,
                          DeliveryNumber = deliveryNumber,
                          DeliveryCompany = order.DeliveryCompany,
                          Action = "删除",
                          Image = image,
                          Source = og,
                          SellerId = order.SellerId,
                      };
                    OrderChange oc = this.orderChangeService.GetByField("OrderGoodsId", og.Id);
                    if (oc != null)
                    {
                        vm.Id = oc.Id;
                    }

                    try
                    {
                        vm.Comment = orderService.GetPopComment(og.OrderId);
                    }
                    catch (Exception ex)
                    {
                        vm.Comment = ex.Message;
                    }
                    this.orderRefuse.Add(vm);
                    Speaker.Speak("已接受");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                e.Handled = true;
                this.tbDeliveryNumber.Text = "";
            }
        }


        private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("是否清空?", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
            {
                return;
            }
            this.orderRefuse.Clear();
        }

        private void btnUpload_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var s = ServiceContainer.GetService<ArriveInDeliveryService>();
                var sc = ServiceContainer.GetService<OrderChangeService>();
                foreach (var item in this.orderRefuse)
                {
                    App.DoEvents();

                    if (item.CreateArriveInDelivery)
                    {
                        item.State = "上传成功";
                        continue;
                    }

                    try
                    {
                        int orderChangeId = ServiceContainer.GetService<OrderChangeService>().Create(item.Source.OrderId, item.Source.Id, item.DeliveryCompany, item.DeliveryNumber, ProxyDelivery.Domain.OrderChangeType.Refused, ProxyDelivery.Domain.OrderChangeReason.Day7, item.Source.Count, "");
                        if (orderChangeId < 0)
                        {
                            throw new Exception("创建退货记录失败");
                        }
                        item.OrderChange = ServiceContainer.GetService<OrderChangeService>().GetById(orderChangeId);
                        Mengsk.ProxyDelivery.Domain.ArriveInDelivery ad = new ProxyDelivery.Domain.ArriveInDelivery
                        {
                            ArriveReason = ProxyDelivery.Domain.ArriveReason.Refused,
                            Comment = item.Comment,
                            CreateTime = DateTime.Now,
                            DeliveryCompany = item.DeliveryCompany,
                            DeliveryNumber = item.DeliveryNumber,
                            GoodsInfo = item.OrderGoodsInfo,
                            Operator = "",
                            OrderChangeId = orderChangeId,
                            OrderGoodsId = item.Source.Id,
                            OrderId = item.Source.OrderId,
                            Id = 0,
                        };
                        s.Insert(ad);
                        //标记收到
                        if (item.Source.Id > 0)
                        {
                            try
                            {
                                sc.MarkRecived(orderChangeId);
                                sc.MarkWaitToVendor(orderChangeId, OrderChangeResultReason.Day7, item.Source.Count, COMMENT, "", "", "", false, false, 0, 0, (item.Source.Price + item.Source.PayedAddPrice) * item.Source.Count, item.OrderGoodsInfo);
                            }
                            catch (Exception ex)
                            {
                                throw new Exception(ex.Message + ", " + item.Source.Id);
                            }
                        }
                        item.Id = orderChangeId;
                        item.State = "上传成功";
                        item.CreateArriveInDelivery = true;
                    }
                    catch (Exception ex)
                    {
                        item.State = ex.Message;
                    }

                    App.DoEvents();
                }
                MessageBox.Show("上传成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Delete_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                OrderRefusedViewModel order = (e.Source as Hyperlink).DataContext as OrderRefusedViewModel;
                if (order == null)
                {
                    return;
                }
                this.orderRefuse.Remove(order);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnModifyPopComment_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                foreach (var item in this.orderRefuse)
                {
                    item.State = "";
                }

                App.DoEvents();

                foreach (var item in this.orderRefuse.GroupBy(obj => obj.Source.OrderId))
                {
                    String state = "标记成功";
                    String comment = "";

                    try
                    {
                        if (item.FirstOrDefault().ModifiedPopComment == false)
                        {
                            comment = item.FirstOrDefault().Comment;
                            string appendComment = DateTime.Now.ToString("MM.dd") + "返回收到，检查完好";
                            if (item.Count() > 1)
                            {
                                appendComment += "[共" + item.Count() + "]";
                            }
                            comment += appendComment;
                            this.orderService.ModifyPopComment(item.Key, ProxyDelivery.Domain.OrderFlag.RED, comment);
                        }
                    }
                    catch (Exception ex)
                    {
                        state = ex.Message;
                    }
                    foreach (var ii in item)
                    {
                        ii.State = state;
                        if (state == "标记成功")
                        {
                            ii.Comment = comment;
                            ii.ModifiedPopComment = true;
                        }
                    }
                    App.DoEvents();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnPrintAll_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                VendorService vs = ServiceContainer.GetService<VendorService>();
                var ocs = new List<OrderChange>();
                foreach (var item in this.orderRefuse)
                {
                    if (item.Id < 1)
                    {
                        throw new Exception("请先生成记录");
                    }
                }
                PrintDevice.PrintOrderReturn(this.orderRefuse.Select(obj => obj.OrderChange).ToArray());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
